import { useState } from "react";

interface UseCheckBoxReturn {
    selected: Set<string>,
    onChange: (event: React.ChangeEvent<HTMLInputElement>) => void
    reset: () => void,
    selectAll: (items: string[]) => void
}

function useCheckBox(): UseCheckBoxReturn {
    const [selected, setSelected] = useState<Set<string>>(new Set());

    const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const { value, checked } = event.target;
        setSelected((prev) => {
            const newSelected = new Set(prev);
            if (checked) {
                newSelected.add(value);
            } else {
                newSelected.delete(value);
            }
            return newSelected;
        });
    };

    const reset = () => {
        setSelected(new Set());
    };

    const selectAll = (items: string[]) => {
        if(selected.size>0){
            reset();
        }else{
            setSelected(new Set(items));
        }
    };

    return {
        selected,
        onChange,
        reset,
        selectAll
    }
}

export default useCheckBox;
